const http = require('http')
const GitTools = require('./Tools/GitTool.js');
const {
    spawn
} = require('child_process');

const server = http.createServer(async (req, res) => {
    // 暂时忽略request method,默认都是GET请求
    res.writeHead(200, { 'Content-Type': 'application/json' });
    console.log(req)
    try {
        switch (req.url) {
            case '/api/test1':
                res.statusCode = 200
                res.write('hello')
                break;
            case '/api/branch':
                var git = new GitTools(`/Users/louers/WebstormProjects/fe-rjreact`);
                const result = await git.childProcess( ["branch"], );
                var current = '';
                var branchs = result.split('\n').map(item => {
                    var reg = new RegExp(/\*/g);
                    if (reg.test(item)) {
                        item = item.replace(reg, '');
                        current = item.trim();
                    }
                    return item.trim();
                }).filter(item => item);
                console.log(branchs)
                res.statusCode = 200
                // res.write(branchs.join("\n"))
                res.end(JSON.stringify({
                    current,
                    branchs
                }))
                break;
            case '/api/testerror':
                throw new Error('I am error.')
                break;
            default:
                res.statusCode = 404
        }
    } catch (err) {
        res.statusCode = 500
        res.write('server Error')
    }
    // res.end()
})

server.listen(3000, () => {
    console.log('connecting....')
})

console.log('server listening at port 3000')